<template>
    <div>
        <a-modal :visible="visible" :width="600" title="常用系统设置" okText="确认" cancelText="取消" @cancel="handleCancel" @ok="handleOk">
            <div class="transfer-name">您可通过鼠标进行拖拽排序（左侧至少保留一个标签）</div>
            <div class="transfer-list">
                <div class="transfer-list-box">
                    <div class="transfer-list-head">
                        <a-checkbox v-model:checked="checkLeftAll" @change="onCheckLeftAllChange" @click.stop="" />
                        <div class="transfer-list-head-name">显示的标签</div>
                        <div class="transfer-list-head-detail">{{ checkedLeftItems.length }}/{{ checkedLeftData.length }}</div>
                    </div>
                    <div class="transfer-list-body" ref="transferLeftListRef">
                        <template v-for="(item, index) in checkedLeftData" :key="index">
                            <div class="list-item">
                                <a-checkbox v-model:checked="item.checked" class="list-item-check" @change="leftCheckItemChange" />
                                <a-tooltip :title="item.system">
                                    <div class="list-item-name">{{ item.system }}</div>
                                </a-tooltip>
                            </div>
                        </template>
                    </div>
                </div>
                <div class="transfer-middle-list">
                    <a-button
                        :disabled="checkedRightItems.length === 0"
                        :class="[checkedRightItems.length > 0 ? 'transfer-middle-button-select' : '']"
                        @click="changePositon('left')"
                    >
                        <template #icon><LeftOutlined /></template>
                    </a-button>
                    <!-- 左边数据必须大于1 -->
                    <a-button
                        :disabled="checkedLeftItems.length === 0 || checkedLeftData.length <= 1"
                        :class="[
                            checkedLeftItems.length > 0 && checkedLeftData.length > 1 ? 'transfer-middle-button-select' : '',
                            'transfer-middle-right-button',
                        ]"
                        @click="changePositon('right')"
                    >
                        <template #icon><RightOutlined /></template>
                    </a-button>
                </div>
                <div class="transfer-list-box">
                    <div class="transfer-list-head">
                        <a-checkbox v-model:checked="checkRightAll" @change="onCheckRightAllChange" />
                        <div class="transfer-list-head-name">隐藏的标签</div>
                        <div class="transfer-list-head-detail">{{ checkedRightItems.length }}/{{ checkedRightData.length }}</div>
                    </div>
                    <div class="transfer-list-body">
                        <div style="padding: 12px 15px 10px 15px">
                            <a-input v-model:value="keyword" placeholder="请输入系统名称" @change="handleSearch">
                                <template #suffix>
                                    <search-outlined style="color: rgba(0, 0, 0, 0.45)" />
                                </template>
                            </a-input>
                        </div>
                        <template v-for="(item, index) in checkedRightData" :key="index">
                            <div class="list-item" style="display: flex; align-items: center">
                                <a-checkbox v-model:checked="item.checked" class="list-item-check" @change="rightCheckItemChange" />
                                <a-tooltip :title="item.system">
                                    <div class="list-item-name">{{ item.system }}</div>
                                </a-tooltip>
                            </div>
                        </template>
                    </div>
                </div>
            </div>
        </a-modal>
    </div>
</template>

<script lang="ts">
import { LeftOutlined, RightOutlined, SearchOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { deepClone } from '@/utils/util';
import { useSortable } from '@/hooks/common/useSortable';
import api from '@/api';
import { defineComponent, reactive, toRefs, ref, unref, getCurrentInstance, nextTick } from 'vue';
export default defineComponent({
    name: 'SysTransfer',
    components: {
        LeftOutlined,
        RightOutlined,
        SearchOutlined
    },
    props: {
        list: { type: Array, default: () => [] },
        targetList: { type: Array, default: () => [] }
    },
    emits: ['success'],
    setup(props, { emit }) {
        const transferLeftListRef = ref<any>();
        const instance: any = getCurrentInstance();
        const state = reactive<any>({
            visible: false,
            checkedLeftData: [], // 左边所有数据
            checkedRightData: [], // 右边所有数据
            checkLeftAll: false,
            checkRightAll: false,
            checkedLeftItems: [], // 左边选择数据
            checkedRightItems: [], // 右边选择数据
            keyword: '' // 搜索
        });
        const open = () => {
            state.keyword = '';
            state.visible = true;
            state.checkedLeftData = [...props.targetList];
            state.checkedRightData = props.list.filter((item: any) => {
                // 匹配list中不在targetList中的选项
                return !props.targetList.find((elem: any) => elem.systemId === item.systemId);
            });
            initSortable();
        };
        const getList = async () => {
            state.checkedLeftData = [];
            state.checkedRightData = [];
        };
        const handleCancel = () => {
            state.visible = false;
        };
        // 保存
        const handleOk = async () => {
            // 确保保存系统不能为空
            if (!state.checkedLeftData.length) {
                message.error('请至少选择一个系统');
                return;
            }
            const query = {
                id: instance.proxy.userInfo.employeeDTO.empId,
                productRequireSystem: JSON.stringify(state.checkedLeftData)
            };
            const { success, errorMsg } = await api.userCustomModel.save(query);
            if (success) {
                emit('success');
            } else {
                message.error(errorMsg);
            }
            handleCancel();
        };
        const changePositon = (type: 'left' | 'right') => {
            // 向左边移动
            if (type === 'left') {
                state.checkedRightItems.forEach((item) => {
                    const index = state.checkedRightData.findIndex((elem) => elem.id === item.id);
                    if (index >= 0) {
                        state.checkedRightData.splice(index, 1);
                    }
                    item.checked = false;
                    state.checkedLeftData.push(item);
                });
                state.checkedRightItems = []; // 清空
                leftCheckItemChange(); // 更新
                rightCheckItemChange(); // 更新
            }
            // 向右边移动
            else {
                state.checkedLeftItems.forEach((item) => {
                    const index = state.checkedLeftData.findIndex((elem) => elem.id === item.id);
                    if (index >= 0) {
                        state.checkedLeftData.splice(index, 1);
                    }
                    item.checked = false;
                    state.checkedRightData.push(item);
                });
                state.checkedLeftItems = []; // 清空
                leftCheckItemChange(); // 更新
                rightCheckItemChange(); // 更新
            }
        };
        // 左边选择点击
        const leftCheckItemChange = () => {
            changeCheckedItems('left');
            if (state.checkedLeftData.length > 0) {
                if (state.checkedLeftItems.length === state.checkedLeftData.length) {
                    state.checkLeftAll = true;
                } else {
                    state.checkLeftAll = false;
                }
            } else {
                state.checkLeftAll = false;
            }
        };
        // 右边选择点击
        const rightCheckItemChange = () => {
            changeCheckedItems('right');
            if (state.checkedRightData.length > 0) {
                if (state.checkedRightItems.length === state.checkedRightData.length) {
                    state.checkRightAll = true;
                } else {
                    state.checkRightAll = false;
                }
            } else {
                state.checkRightAll = false;
            }
        };

        const changeCheckedItems = (type) => {
            if (type === 'left') {
                state.checkedLeftItems = state.checkedLeftData.filter((item) => item.checked);
            } else {
                state.checkedRightItems = state.checkedRightData.filter((item) => item.checked);
            }
        };
        const onCheckLeftAllChange = (val) => {
            state.checkedLeftData.forEach((item, index) => {
                state.checkedLeftData[index] = {
                    ...state.checkedLeftData[index],
                    checked: val.target.checked
                };
            });
            changeCheckedItems('left');
        };
        const onCheckRightAllChange = (val) => {
            state.checkedRightData.forEach((item, index) => {
                state.checkedRightData[index] = {
                    ...state.checkedRightData[index],
                    checked: val.target.checked
                };
            });
            changeCheckedItems('right');
        };
        // 自定义模糊查询
        const handleSearch = (e: any) => {
            const val = e.target.value;
            const list = props.list.filter((item: any) => {
                // 匹配list中不在左侧中的选项
                return !state.checkedLeftData.find((elem) => elem.id === item.id);
            });
            if (val) {
                state.checkedRightData = list.filter((item: any) => item.system.indexOf(val) >= 0);
            } else {
                state.checkedRightData = list;
            }
        };
        const initSortable = () => {
            nextTick(() => {
                const { initSortable } = useSortable(unref(transferLeftListRef), {
                    onUpdate: (evt: any) => {
                        const { oldIndex, newIndex } = evt;
                        const list: any = deepClone(state.checkedLeftData);
                        const val = list.splice(oldIndex, 1)[0];
                        list.splice(newIndex, 0, val);
                        state.checkedLeftData = [];
                        nextTick(() => {
                            state.checkedLeftData = [...list];
                        });
                    }
                });
                initSortable();
            });
        };
        return {
            transferLeftListRef,
            ...toRefs(state),
            open,
            getList,
            handleCancel,
            handleOk,
            changePositon,
            onCheckLeftAllChange,
            onCheckRightAllChange,
            handleSearch,
            leftCheckItemChange,
            rightCheckItemChange
        };
    }
});
</script>

<style scoped lang="less">
.transfer-name {
    font-size: 12px;
    padding-bottom: 5px;
    color: #aaa;
}

.transfer-list {
    user-select: none;
    display: flex;
    align-items: center;
    .transfer-list-box {
        // flex: 1;
        width: 250px;
        border: 1px solid #e6e6e6;
        border-radius: 2px;
        height: 300px;
        position: relative;
    }
    .transfer-middle-list {
        width: 50px;
        text-align: center;
        button {
            border: 1px solid #cccccc;
            width: 30px;
            height: 30px;
            // border-radius: 17px;
            background-color: #f5f7fa;
        }
        .transfer-middle-icon {
            color: #cccccc;
            font-size: 14px;
        }
        .transfer-middle-right-button {
            margin-top: 15px;
            margin-left: 0;
        }

        .transfer-middle-button-select {
            border: 1px solid #e6e6e6 !important;
            background-color: @primary-color !important;
            color: white !important;
            .transfer-middle-icon {
                color: white !important;
            }
        }
    }
    .transfer-list-head {
        display: flex;
        align-items: center;
        padding: 15px;
        border-bottom: 1px dashed #e6e6e6;
        font-size: 13px;
        .transfer-list-head-name {
            color: #333;
            flex: 1;
            margin: 0 8px;
        }
        .transfer-list-head-detail {
            color: #aaa;
        }
    }
    .transfer-list-body {
        height: 240px;
        position: relative;
        overflow-y: auto;
    }

    .list-item {
        padding: 5px 15px;
        display: flex;
        align-items: center;
        background-color: white;
        height: 38px;
        cursor: move;
        &:hover {
            background: #eaf5fe;
        }
        .list-item-check {
            margin-right: 8px;
        }
        .list-item-name {
            font-size: 13px;
            color: #333;
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    }
}
</style>
